package com.us.usws.batch.resimp;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.iwsh.core.db.DBExecutor;
import net.iwsh.core.exception.DBException;

import com.us.usws.batch.BatchUtils;
import com.us.usws.common.SiteConstants;
import com.us.usws.model.domain.base.BaseDict;
import com.us.usws.model.domain.base.BaseVideoCat;
import com.us.usws.model.domain.video.Video;
import com.us.usws.model.domain.video.VideoFile;
import com.us.usws.model.flat.channel.DOChannel;

public class BatchBdao {

	private static final String[] CLEAN_CHANNEL_TABLES = { "hv_channel_video_link", "box_theme_meeting_link", "box_theme_video_link",
			"box_theme", "hv_meeting_attendee", "hv_meeting", "hv_channel" };

	private static final String SQL_INSERT_CHANNEL = "insert into hv_channel(uid,is_idx_channel,name,parent_uid,picture,channel_type_dsid,ui_type,is_valid,seq_num,target_role,description,create_by_uid,create_date,last_upd_by_uid,last_upd_date,relate_cat,video_quality,video_from,metting_type,metting_status, plate_picture) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

	private static final String[] CLEAN_VIDEO_TABLES = { "hv_video_attendee", "hv_video_auth_log", "hv_video_comment", "hv_video_cat_link",
			"hv_video_extattr", "hv_video_play_log", "hv_channel_video_link", "hv_video", "hv_video_file" };
	//private static final String[] CLEAN_VIDEO_CATS = { "hv_video_type_cat_link", "hvb_video_cat", "hv_video_cat_link" };

	private static final String SQL_INSERT_VIDEOFILE = "insert into hv_video_file(uid,orig_file_name,snapshot,file_size,mime_type,play_len,file_ext,create_by_uid,create_date,last_upd_by_uid,last_upd_date) values (?,?,?,?,?,?,?,?,?,?,?)";
	private static final String SQL_INSERT_VIDEO = "insert into hv_video(uid,file_uid,name,type_sid,tags,auth_status_dsid,seq_num,create_by_uid,create_date,last_upd_by_uid,last_upd_date,description) values (?,?,?,?,?,?,?,?,?,?,?,?)";
	private static final String SQL_INSERT_VIDEO_CAT_LINK = "insert into hv_video_cat_link(video_uid,cat_uid) values (?,?)";

	private static final String SQL_INSERT_CHANNEL_VIDEO_LINK = "insert into hv_channel_video_link(channel_uid,video_uid,seq_num,is_hot,create_by_uid,create_date) values(?,?,?,?,?,?)";

	private static final String SQL_INSERT_REGION = "insert into hvb_dict(uid,domain,code,name,seq_num,sep_id,extra_val,create_by_uid,create_date) values (?,?,?,?,?,?,?,?,?)";

	private static final String CLEAN_REGION_IN_DICT = "delete from hvb_dict where domain=?";

	/**
	 * Insert one row.
	 */
	public void createChannels(Collection<DOChannel> channels, boolean cleanBeforeInsert) {
		DBExecutor dbe = new DBExecutor();

		dbe.startTransaction();
		try {

			if (cleanBeforeInsert) {
				for (String each : CLEAN_CHANNEL_TABLES) {
					String sql = "delete from " + each;
					dbe.executeBatch(sql);
				}
			}
			//insert
			for (DOChannel channel : channels) {
				dbe.executeBatch(SQL_INSERT_CHANNEL, channel.getUid(), channel.getIsIdxChannel(), channel.getName(),
						channel.getParentUid(), channel.getPicture(), channel.getChannelTypeDsid(), channel.getUiType(),
						channel.getIsValid(), channel.getSeqNum(), channel.getTargetRole(), channel.getDescription(),
						channel.getCreateByUid(), channel.getCreateDate(), channel.getLastUpdByUid(), channel.getLastUpdDate(),
						channel.getRelateCat(), channel.getVideoQuality(), channel.getVideoFrom(), channel.getMettingType(),
						channel.getMettingStatus(), channel.getPlatePicture());
			}

		} catch (Exception e) {
			//error
			dbe.rollbackTransaction();
			throw new DBException("Error when batch insert channels.", e);
		}

		dbe.commitTransaction();
	}

	public void createVidoes(List<Video> videos, Map<String, List<String>> channelVideoLinks, boolean cleanBeforeInsert) {
		DBExecutor dbe = new DBExecutor();
		Date now = new Date();
		dbe.startTransaction();
		try {

			if (cleanBeforeInsert) {
				for (String each : CLEAN_VIDEO_TABLES) {
					String sql = "delete from " + each;
					dbe.executeBatch(sql);
				}
			}

			//insert
			for (Video video : videos) {
				VideoFile videoFile = video.getVideoFile();
				dbe.executeBatch(SQL_INSERT_VIDEOFILE, videoFile.getUid(), videoFile.getOrigFileName(), videoFile.getSnapshot(),
						videoFile.getFileSize(), videoFile.getMimeType(), videoFile.getPlayLen(), videoFile.getFileExt(),
						videoFile.getCreateByUid(), videoFile.getCreateDate(), videoFile.getLastUpdByUid(), videoFile.getLastUpdDate());

				dbe.executeBatch(SQL_INSERT_VIDEO, video.getUid(), video.getFileUid(), video.getName(), video.getTypeSid(),
						video.getTags(), video.getAuthStatusDsid(), video.getSeqNum(), video.getCreateByUid(), video.getCreateDate(),
						video.getLastUpdByUid(), video.getLastUpdDate(), video.getDescription());

				if (video.getCategories() != null) {
					for (BaseVideoCat cat : video.getCategories()) {
						dbe.executeBatch(SQL_INSERT_VIDEO_CAT_LINK, video.getUid(), cat.getUid());
					}
				}

			}

			//channel links
			for (String channelUid : channelVideoLinks.keySet()) {
				int idx = 0;
				for (String videoUid : channelVideoLinks.get(channelUid)) {
					idx++;
					dbe.executeBatch(SQL_INSERT_CHANNEL_VIDEO_LINK, channelUid, videoUid, idx, SiteConstants.STR_BOOLEAN_YES,
							BatchUtils.ADMIN_UID, now);
				}
			}

		} catch (Exception e) {
			//error
			dbe.rollbackTransaction();
			throw new DBException("Error when batch insert videos.", e);
		}

		dbe.commitTransaction();
	}

	public void createRegionsIntoDict(List<BaseDict> dicts) {
		DBExecutor dbe = new DBExecutor();
		dbe.startTransaction();
		try {

			dbe.executeBatch(CLEAN_REGION_IN_DICT, SiteConstants.DICT_DOMAIN_REGION);

			//insert
			for (BaseDict each : dicts) {

				dbe.executeBatch(SQL_INSERT_REGION, each.getUid(), each.getDomain(), each.getCode(), each.getName(), each.getSeqNum(),
						each.getSepId(), each.getExtraVal(), each.getCreateByUid(), each.getCreateDate());
			}

		} catch (Exception e) {
			//error
			dbe.rollbackTransaction();
			throw new DBException("Error when batch insert regions.", e);
		}

		dbe.commitTransaction();
	}

}
